/*
* axios 封装
*/
import axios from 'axios'
import config from './../config'
import { ElMessage } from 'element-plus'
import router from "../router";
import storage from "../utils/storage"

const TOKEN_INVALID = 'Token认证失败， 请重新登录'
const NETWORK_ERROR = '网络异常'

const service = axios.create({
    baseURL: config.baseApi,
    timeout: 5000
})

// 请求拦截
service.interceptors.request.use(
    config => {
        if(!config.headers.Authorization){
            config.headers.Authorization = 'Bearer '+ storage.getItem('token')
        }
        return config
    },
    error => {
        console.log(error) // for debug
        return Promise.reject(error)
    },
)

// 响应拦截
service.interceptors.response.use(
    response =>{
        const { code, data, msg} = response.data
        if (code === 200) {
            return data
        } else if (code === 50001) { // 鉴权失败
            ElMessage.error(TOKEN_INVALID)
            router.push('/login')
            return Promise.reject(TOKEN_INVALID)
        } else {
            ElMessage.error(msg || NETWORK_ERROR)
            return Promise.reject(msg || NETWORK_ERROR)
        }
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)
function request(options) {
    options.method = options.method || 'get'
    if (options.method.toLowerCase() === 'get') {
        options.params = options.data
    }
    // mock配置
    let isMock = config.mock
    if (typeof options.mock !== 'undefined') {
        isMock = options.mock
    }
    if (config.env === 'prod') {
        service.defaults.baseURL = config.baseApi
    } else {
        service.defaults.baseURL = isMock ? config.mockApi : config.baseApi
    }
    return service(options)
}

['get', 'post', 'put', 'delete', 'patch'].forEach(item => {
    request[item] = (url, data, options) => {
        return request({
            url,
            data,
            method: item,
            ...options
        })
    }
})

export default request
